using Microsoft.EntityFrameworkCore;
using RiceShop.Models;

namespace RiceShop.Services
{
    /// <summary>
    /// 优惠券服务接口
    /// </summary>
    public interface ICouponService
    {
        /// <summary>
        /// 获取优惠券列表
        /// </summary>
        /// <param name="status">优惠券状态（可选）</param>
        Task<IEnumerable<Coupon>> GetCouponsAsync(byte? status);

        /// <summary>
        /// 领取优惠券
        /// </summary>
        Task ReceiveCouponAsync(long userId, long couponId);

        /// <summary>
        /// 使用优惠券
        /// </summary>
        Task UseCouponAsync(long userId, long couponId);

        /// <summary>
        /// 获取用户优惠券
        /// </summary>
        Task<UserCoupon?> GetUserCouponAsync(long couponId);
    }

    /// <summary>
    /// 优惠券服务实现类
    /// 提供优惠券的查询、领取、使用等功能
    /// </summary>
    public class CouponService : ICouponService
    {
        private readonly ApplicationDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public CouponService(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取优惠券列表
        /// 可根据状态筛选：0-已失效，1-生效中
        /// </summary>
        public async Task<IEnumerable<Coupon>> GetCouponsAsync(byte? status)
        {
            var query = _context.Coupons.AsQueryable();
            
            if (status.HasValue)
            {
                query = query.Where(c => c.Status == status.Value);
            }

            return await query.ToListAsync();
        }

        /// <summary>
        /// 用户领取优惠券
        /// 仅能领取状态为1（生效中）的优惠券
        /// </summary>
        public async Task ReceiveCouponAsync(long userId, long couponId)
        {
            var coupon = await _context.Coupons
                .FirstOrDefaultAsync(c => c.Id == couponId && c.Status == 1)
                ?? throw new KeyNotFoundException("优惠券不存在或已失效");

            var userCoupon = new UserCoupon
            {
                UserId = userId,
                CouponId = couponId,
                Status = 0 // 未使用
            };

            _context.UserCoupons.Add(userCoupon);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 使用优惠券
        /// 将优惠券状态更新为已使用，并记录使用时间
        /// </summary>
        public async Task UseCouponAsync(long userId, long couponId)
        {
            var userCoupon = await _context.UserCoupons
                .FirstOrDefaultAsync(uc => uc.UserId == userId && uc.CouponId == couponId && uc.Status == 0)
                ?? throw new KeyNotFoundException("优惠券不存在或已使用");

            userCoupon.Status = 1; // 已使用
            userCoupon.UseTime = DateTime.Now;
            
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取用户优惠券
        /// </summary>
        public async Task<UserCoupon?> GetUserCouponAsync(long couponId)
        {
            return await _context.UserCoupons
                .Include(uc => uc.Coupon)
                .FirstOrDefaultAsync(uc => 
                    uc.CouponId == couponId && 
                    uc.Status == 0); // 0:未使用
        }
    }
} 